<?php

namespace app\controller\adminapi\open;

use app\common\model\open\Open as OpenModel;
use app\common\model\platform\PlatformAppOpen;
use app\common\services\table\DataTable;
use FormBuilder\Driver\CustomComponent;
use hiduoke\controller\AdminController;
use hiduoke\services\CloudServer;
use hiduoke\services\FormBuilder as Form;

/**
 * Notes: 第三方平台管理 TODO 这里需要完善，可以把douyin和微信合并到这个文件一起处理
 * Create by :  刘泓宾<514660094@qq.com>
 * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
 * Created on:  2025/8/6 03:31
 */
class Open extends AdminController
{
    /**
     * @var PlatformAppOpen
     */
    public $model;

    /**
     * @var CloudServer
     */
    public $cloud;

    public function initialize()
    {
        $this->model = new OpenModel();
        $this->cloud = new CloudServer();
    }

    public function getMinAppOpenList()
    {
        $res = $this->model->getPageList();
        return $this->success($res['count'], $res['data']);
    }

    /**
     * 微信小程序服务商管理端配置
     * @param $id
     * @param $type
     * @return \think\response\Json
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function form($id = 0, $type = 'wx')
    {
        $rule = array();
        //创建表单
        $row = $this->model->findOrEmpty($id); //创建表单
        $form = Form::createForm("/adminapi/open/weChatMini/save?id=" . $id)->setMethod("POST");
        //新增表单
        $rule[] = Form::input('name', '应用名称', $row['name'] ?? "")->required();
        $rule[] = Form::dkImage('logo', '应用图标', $row['logo'] ?? "")->required();
        $rule[] = Form::hidden('type', $type);

        if ($type == 'wx') {
            //第三方平台信息
            $rule[] = Form::input("config_app_id", " AppID", $row['config']['app_id'] ?? '')->effect(['help' => '微信开放平台第三方平台 AppID'])->required();
            $rule[] = Form::input('config_secret', ' AppSecret', $row['config']['secret'] ?? '')->effect(['help' => '微信开放平台第三方平台 AppSecret'])->required();
            // 授权流程相关
            $rule[] = Form::input("config_token", "消息校验 Token", $row['config']['token'] ?? '')->effect(['help' => '用于验证消息来源的 Token，长度为 3-32 个字符，由字母和数字组成'])->required();
            $rule[] = Form::input("config_aes_key", "消息加解密密钥", $row['config']['aes_key'] ?? '')->effect(['help' => '用于消息加解密，长度固定为 43 个字符，由字母和数字组成'])->required();
            if ($id) {
                $oauth_url = request()->domain() . '/wxmin/open/event/id/' . $id;
                $message_event_url = request()->domain() . '/wxmin/open/message_event/id/' . $id . '/appid/$APPID$';
            } else {
                $oauth_url = "请提交保存后打开";
                $message_event_url = "请提交保存后打开";
            }
            $rule[] = Form::dkCopyInput("oauth_url", '授权事件接收', $oauth_url)
                ->effect(['help' => '将当前地址填写至微信开放平台第三方平台设置中的授权事件接收 URL，用于接收授权成功、取消授权等通知'])
                ->disabled(true);
            // 授权后实现业务
            $rule[] = Form::dkCopyInput("message_event_url", '消息与事件接收', $message_event_url)
                ->effect(['help' => '将当前地址填写至微信开放平台第三方平台设置中，用于接收已授权小程序的消息和事件推送'])
                ->disabled(true);
        } else if ($type == 'dy') {
//            $rule[] = Form::input('config_template_id', '模板ID', $row['config']['template_id'] ?? '');
//            $rule[] = Form::input('config_user_desc', '描述', $row['config']['user_desc'] ?? '');
//            $rule[] = Form::input('config_user_version', '版本号', $row['config']['user_version'] ?? '');
            // 选择默认授权方式
//            $rule[] = Form::radio("config_auth_type", "授权方式", $row['config']['auth_type'] ?? 'manual')
//                ->button()
//                ->size('small')
//                ->options(
//                    [
//                        ['label' => '自建小程序（手动配置）', 'value' => 'manual'],
//                        ['label' => '用户自由选择配置方式', 'value' => 'auto'],
//                        ['label' => '抖音服务商链接授权', 'value' => 'open'],
//                    ]
//                )->effect(['help' => '当前未对外部用户开放该功能']);
            //开发者ID
            $rule[] = Form::input("config_component_appid", "appid", $row['config']['component_appid'] ?? '')->effect(['help' => '第三方小程序应用 appid'])->required();
            $rule[] = Form::input('config_component_appsecret', 'APPSecret', $row['config']['component_appsecret'] ?? '')->effect(['help' => '第三方小程序应用 APPSecret'])->required();
            if ($id) {
                $oauth_url = request()->domain() . '/dy/open/event/id/' . $id;
                $message_event_url = request()->domain() . '/dy/open/message_event/id/' . $id . '/appid/$APPID$/cgi';
            } else {
                $oauth_url = "请提交保存后打开";
                $message_event_url = "请提交保存后打开";
            }


            $rule[] = Form::input("config_token", "TOKEN", $row['config']['token'] ?? '')->effect(['help' => '消息验证 TOKEN 服务商在代授权小程序接收到消息后，用来验证信息，最长为 32 位，只能是大小写字母和数字'])->required();
            $rule[] = Form::input("config_key", "key", $row['config']['key'] ?? '')->effect(['help' => '消息加密解密 KEY 服务商在代授权小程序接收到消息后，用来解密消息，必须是长度为 43 的字符串，只能是大小写字母和数字'])->required();
            $rule[] = Form::dkCopyInput("oauth_url", '授权事件接收', $oauth_url)
                ->effect(['help' => '将当前地址填写至授权事件接收 URL，通过该 URL 接收小程序授权成功通知、授权解除通知，也用于接收 component_ticket'])
                ->disabled(true);
            // 授权后实现业务
            $rule[] = Form::dkCopyInput("message_event_url", '消息与事件接收', $message_event_url)
                ->effect(['help' => '将当前地址填写至授权事件接收 URL，通过该 URL 接收已授权小程序的消息和事件推送'])
                ->disabled(true);
        }

        $title = !$id ? "新增" : "编辑";
        $form->setTitle($title)->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }


    public function table()
    {
        $DataTable = (new DataTable($this->model));
        if ($this->request->param('recycle')) {
            // 回收站
            $DataTable->field([$this->model->getPk(), 'delete_time']);
        }
        $column = $DataTable
            ->setFilterFields(['appsecret', 'config', 'other_data', 'addon_name'])
            ->setField('logo', ['render' => 'image'])
            ->setField('type', ['render' => 'slot'])
            ->setField('addon_name', ['render' => 'tag'])
            ->operation(['width' => '300px', 'render' => 'buttons', 'prop' => 'operation', 'label' => '操作'])->create();
        return $this->success('ok', ['column' => $column, 'pk' => $this->model->getPk()]);
    }

    public function index()
    {
        if ($this->request->param('select')) {
            return $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where(['type' => input('type', 'wx')])
            ->order($order)
            ->paginate($limit);
        return $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }

    public function save()
    {
        $id = input('id', 0);
        $row = $this->model->findOrEmpty($id);
        $formData = getFormData();
        $row->save($formData);
        if ($id) {
            return $this->success("保存成功");
        } else {
            return $this->success('新增成功');
        }
    }
}
